/**
 * 加载UI管理器 - 控制详细的加载进度界面
 */
export class LoadingUIManager {
    constructor() {
        this.elements = this.getElements();
        this.modelItems = new Map();
        this.stats = {
            total: 0,
            loaded: 0,
            fromCache: 0,
            fromNetwork: 0,
            totalSize: 0,
            errors: []
        };
        
        this.isVisible = true;
        this.hideTimeout = null;
        
        // 确认相关
        this.requireConfirmation = true;
        this.isLoadingComplete = false;
        this.onConfirmCallback = null;
        
        // 初始化事件监听
        this.initEventListeners();
    }
    
    /**
     * 获取DOM元素
     */
    getElements() {
        return {
            screen: document.getElementById('loading-screen'),
            subtitle: document.getElementById('loading-subtitle'),
            overallPercentage: document.getElementById('overall-percentage'),
            overallProgress: document.getElementById('overall-progress'),
            overallInfo: document.getElementById('overall-info'),
            currentModelName: document.getElementById('current-model-name'),
            modelPercentage: document.getElementById('model-percentage'),
            modelProgress: document.getElementById('model-progress'),
            modelInfo: document.getElementById('model-info'),
            loadedCount: document.getElementById('loaded-count'),
            totalCount: document.getElementById('total-count'),
            cacheCount: document.getElementById('cache-count'),
            networkCount: document.getElementById('network-count'),
            dataSize: document.getElementById('data-size'),
            modelItems: document.getElementById('model-items'),
            loadingErrors: document.getElementById('loading-errors'),
            errorList: document.getElementById('error-list'),
            // 确认相关元素
            loadingConfirmation: document.getElementById('loading-confirmation'),
            confirmationMessage: document.getElementById('confirmation-message'),
            confirmationButton: document.getElementById('confirmation-button'),
            // 设置开关相关元素
            settingsToggle: document.getElementById('settings-toggle'),
            confirmationToggle: document.getElementById('confirmation-toggle')
        };
    }
    
    /**
     * 初始化事件监听器
     */
    initEventListeners() {
        // 确认按钮点击事件
        if (this.elements.confirmationButton) {
            this.elements.confirmationButton.addEventListener('click', () => {
                this.handleConfirmation();
            });
        }
        
        // 确认开关切换事件
        if (this.elements.confirmationToggle) {
            this.elements.confirmationToggle.addEventListener('click', () => {
                this.toggleConfirmationRequirement();
            });
        }
        
        // 从本地存储读取设置
        this.loadSettings();
    }
    
    /**
     * 加载设置
     */
    loadSettings() {
        const saved = localStorage.getItem('kokomi3d-settings');
        if (saved) {
            try {
                const settings = JSON.parse(saved);
                this.requireConfirmation = settings.requireConfirmation !== false; // 默认为true
            } catch (error) {
                console.warn('加载设置失败:', error);
            }
        }
        
        // 更新开关状态
        this.updateToggleState();
    }
    
    /**
     * 保存设置
     */
    saveSettings() {
        const settings = {
            requireConfirmation: this.requireConfirmation
        };
        
        try {
            localStorage.setItem('kokomi3d-settings', JSON.stringify(settings));
        } catch (error) {
            console.warn('保存设置失败:', error);
        }
    }
    
    /**
     * 切换确认要求
     */
    toggleConfirmationRequirement() {
        this.requireConfirmation = !this.requireConfirmation;
        this.updateToggleState();
        this.saveSettings();
        
        console.log(`确认要求已${this.requireConfirmation ? '开启' : '关闭'}`);
        
        // 如果当前加载已完成且刚关闭确认，自动进入
        if (!this.requireConfirmation && this.isLoadingComplete) {
            this.handleConfirmation();
        }
    }
    
    /**
     * 更新开关状态
     */
    updateToggleState() {
        if (this.elements.confirmationToggle) {
            if (this.requireConfirmation) {
                this.elements.confirmationToggle.classList.add('active');
            } else {
                this.elements.confirmationToggle.classList.remove('active');
            }
        }
    }
    
    /**
     * 处理确认
     */
    handleConfirmation() {
        if (this.onConfirmCallback) {
            this.onConfirmCallback();
        }
        
        this.hide(0); // 立即隐藏
    }
    
    /**
     * 设置确认回调
     * @param {Function} callback - 确认后的回调函数
     */
    setConfirmCallback(callback) {
        this.onConfirmCallback = callback;
    }
    
    /**
     * 显示加载界面
     */
    show() {
        if (this.elements.screen) {
            this.elements.screen.classList.remove('hidden');
            this.isVisible = true;
            
            if (this.hideTimeout) {
                clearTimeout(this.hideTimeout);
                this.hideTimeout = null;
            }
        }
    }
    
    /**
     * 隐藏加载界面
     * @param {number} delay - 延迟时间（毫秒）
     */
    hide(delay = 1000) {
        if (!this.isVisible) return;
        
        this.hideTimeout = setTimeout(() => {
            if (this.elements.screen) {
                this.elements.screen.classList.add('hidden');
                this.isVisible = false;
                
                // 在动画完成后完全隐藏
                setTimeout(() => {
                    if (this.elements.screen) {
                        this.elements.screen.style.display = 'none';
                    }
                }, 500);
            }
        }, delay);
    }
    
    /**
     * 初始化加载过程
     * @param {Array} models - 模型列表
     */
    initializeLoading(models) {
        this.stats.total = models.length;
        this.stats.loaded = 0;
        this.stats.fromCache = 0;
        this.stats.fromNetwork = 0;
        this.stats.totalSize = 0;
        this.stats.errors = [];
        
        this.updateElements({
            subtitle: models.length > 0 ? `正在预加载 ${models.length} 个模型...` : '正在初始化场景...',
            overallInfo: '准备加载模型...',
            totalCount: models.length
        });
        
        // 创建模型项
        this.createModelItems(models);
        
        // 重置进度条
        this.updateProgress(0, 0);
        
        console.log(`LoadingUI: 初始化加载，共 ${models.length} 个模型`);
    }
    
    /**
     * 创建模型项列表
     * @param {Array} models - 模型列表
     */
    createModelItems(models) {
        if (!this.elements.modelItems) return;
        
        this.elements.modelItems.innerHTML = '';
        this.modelItems.clear();
        
        if (models.length === 0) {
            this.elements.modelItems.innerHTML = '<div style="text-align: center; color: rgba(255,255,255,0.5); padding: 20px;">无需加载外部模型</div>';
            return;
        }
        
        models.forEach(model => {
            const item = document.createElement('div');
            item.className = 'model-item';
            item.innerHTML = `
                <div class="model-name">${model.name || model.id}</div>
                <div class="model-status">等待</div>
            `;
            
            this.elements.modelItems.appendChild(item);
            this.modelItems.set(model.id, {
                element: item,
                status: 'waiting'
            });
        });
    }
    
    /**
     * 更新总体进度
     * @param {number} progress - 进度值 (0-1)
     * @param {number} loaded - 已加载数量
     */
    updateProgress(progress, loaded) {
        const percentage = Math.round(progress * 100);
        
        this.updateElements({
            overallPercentage: `${percentage}%`,
            overallProgress: `${percentage}%`,
            overallInfo: loaded > 0 ? `已完成 ${loaded}/${this.stats.total} 个模型` : '准备中...',
            loadedCount: loaded
        });
        
        this.stats.loaded = loaded;
    }
    
    /**
     * 更新当前模型进度
     * @param {Object} modelInfo - 模型信息
     */
    updateModelProgress(modelInfo) {
        const {
            modelId,
            modelName,
            progress = 0,
            fromCache = false,
            loadProgress = null
        } = modelInfo;
        
        const percentage = Math.round(progress * 100);
        
        this.updateElements({
            currentModelName: modelName || modelId,
            modelPercentage: `${percentage}%`,
            modelProgress: `${percentage}%`,
            modelInfo: fromCache ? '从缓存加载...' : (loadProgress ? 
                `网络加载: ${this.formatBytes(loadProgress.loaded)}/${this.formatBytes(loadProgress.total)}` : 
                '网络加载...')
        });
        
        // 更新模型项状态
        this.updateModelItemStatus(modelId, 'loading', fromCache ? '缓存' : '网络');
    }
    
    /**
     * 模型加载完成
     * @param {string} modelId - 模型ID
     * @param {boolean} fromCache - 是否从缓存加载
     * @param {number} size - 模型大小
     */
    onModelComplete(modelId, fromCache = false, size = 0) {
        if (fromCache) {
            this.stats.fromCache++;
        } else {
            this.stats.fromNetwork++;
            this.stats.totalSize += size;
        }
        
        this.updateModelItemStatus(modelId, 'completed', fromCache ? '缓存' : '网络');
        
        // 更新统计信息
        this.updateElements({
            cacheCount: this.stats.fromCache,
            networkCount: this.stats.fromNetwork,
            dataSize: this.formatBytes(this.stats.totalSize)
        });
        
        console.log(`LoadingUI: 模型 ${modelId} 加载完成 (${fromCache ? '缓存' : '网络'})`);
    }
    
    /**
     * 模型加载错误
     * @param {string} modelId - 模型ID
     * @param {string} error - 错误信息
     */
    onModelError(modelId, error) {
        this.stats.errors.push({ modelId, error, timestamp: Date.now() });
        this.updateModelItemStatus(modelId, 'error', '错误');
        
        // 显示错误信息
        this.showErrors();
        
        console.error(`LoadingUI: 模型 ${modelId} 加载失败:`, error);
    }
    
    /**
     * 更新模型项状态
     * @param {string} modelId - 模型ID
     * @param {string} status - 状态
     * @param {string} label - 标签文本
     */
    updateModelItemStatus(modelId, status, label) {
        const item = this.modelItems.get(modelId);
        if (!item) return;
        
        const statusElement = item.element.querySelector('.model-status');
        if (statusElement) {
            statusElement.textContent = label;
            statusElement.className = `model-status ${status === 'loading' ? (label === '缓存' ? 'cache' : 'network') : status}`;
        }
        
        item.element.className = `model-item ${status}`;
        item.status = status;
    }
    
    /**
     * 显示错误信息
     */
    showErrors() {
        if (this.stats.errors.length === 0) return;
        
        if (!this.elements.loadingErrors || !this.elements.errorList) return;
        
        this.elements.errorList.innerHTML = '';
        
        this.stats.errors.forEach(error => {
            const errorItem = document.createElement('div');
            errorItem.className = 'error-item';
            errorItem.innerHTML = `
                <strong>${error.modelId}:</strong> ${error.error}
            `;
            this.elements.errorList.appendChild(errorItem);
        });
        
        this.elements.loadingErrors.style.display = 'block';
    }
    
    /**
     * 加载完成
     * @param {Object} result - 加载结果
     */
    onLoadingComplete(result) {
        const { stats, loadTime, success } = result;
        
        this.isLoadingComplete = true;
        
        const message = success ? 
            `加载完成！用时 ${loadTime.toFixed(2)}s` : 
            '加载完成，但有部分错误';
            
        this.updateElements({
            subtitle: message,
            overallInfo: `总计: ${stats.totalModels} | 缓存: ${stats.loadedFromCache} | 网络: ${stats.loadedFromNetwork}`,
            currentModelName: success ? '✅ 所有模型已就绪' : '⚠️ 部分模型加载失败',
            modelInfo: success ? '可以开始使用场景' : '部分功能可能受影响'
        });
        
        // 根据设置决定是否显示确认按钮
        if (this.requireConfirmation) {
            this.showConfirmation(success);
        } else {
            // 不需要确认，直接进入
            this.hide(success ? 1500 : 3000);
            if (this.onConfirmCallback) {
                setTimeout(() => {
                    this.onConfirmCallback();
                }, success ? 1500 : 3000);
            }
        }
        
        console.log(`LoadingUI: 加载完成，成功: ${success}，需要确认: ${this.requireConfirmation}`);
    }
    
    /**
     * 显示确认按钮
     * @param {boolean} success - 加载是否成功
     */
    showConfirmation(success) {
        if (!this.elements.loadingConfirmation || !this.elements.confirmationMessage || !this.elements.confirmationButton) {
            return;
        }
        
        // 更新确认消息
        if (success) {
            this.elements.confirmationMessage.innerHTML = '✅ 所有资源加载完成！准备进入3D世界';
            this.elements.confirmationButton.textContent = '进入场景';
            this.elements.confirmationButton.disabled = false;
        } else {
            this.elements.confirmationMessage.innerHTML = '⚠️ 部分资源加载失败，但仍可体验基础功能';
            this.elements.confirmationButton.textContent = '仍要进入';
            this.elements.confirmationButton.disabled = false;
        }
        
        // 显示确认区域
        this.elements.loadingConfirmation.classList.add('visible');
        
        console.log('显示确认按钮');
    }
    
    /**
     * 更新UI元素
     * @param {Object} updates - 更新数据
     */
    updateElements(updates) {
        Object.entries(updates).forEach(([key, value]) => {
            const element = this.elements[key];
            if (!element) return;
            
            if (key.includes('Progress')) {
                // 进度条
                element.style.width = value;
            } else {
                // 文本内容
                element.textContent = value;
            }
        });
    }
    
    /**
     * 格式化字节大小
     * @param {number} bytes - 字节数
     * @returns {string} 格式化后的大小
     */
    formatBytes(bytes) {
        if (bytes === 0) return '0B';
        
        const k = 1024;
        const sizes = ['B', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + sizes[i];
    }
    
    /**
     * 设置自定义消息
     * @param {string} message - 消息内容
     */
    setMessage(message) {
        this.updateElements({
            subtitle: message
        });
    }
    
    /**
     * 获取加载统计信息
     * @returns {Object} 统计信息
     */
    getStatistics() {
        return { ...this.stats };
    }
    
    /**
     * 重置加载界面
     */
    reset() {
        this.stats = {
            total: 0,
            loaded: 0,
            fromCache: 0,
            fromNetwork: 0,
            totalSize: 0,
            errors: []
        };
        
        this.modelItems.clear();
        
        if (this.elements.modelItems) {
            this.elements.modelItems.innerHTML = '';
        }
        
        if (this.elements.loadingErrors) {
            this.elements.loadingErrors.style.display = 'none';
        }
        
        this.updateProgress(0, 0);
        
        console.log('LoadingUI: 已重置');
    }
    
    /**
     * 销毁加载UI管理器
     */
    dispose() {
        if (this.hideTimeout) {
            clearTimeout(this.hideTimeout);
            this.hideTimeout = null;
        }
        
        this.modelItems.clear();
        
        console.log('LoadingUIManager 已销毁');
    }
}
